#!/usr/bin/env python

import os
import imp
import sys
import ConfigParser
from sc_engine import run_as_script

def show_usage():
    prog_name = os.path.basename(sys.argv[0])
    msg = "usage: %s script_name config_filename" % prog_name
    raise SystemExit(msg)

def parse_configs(config_filename):
    configs = {}

    config_parser = ConfigParser.SafeConfigParser()
    config_parser.read(config_filename)

    for section in config_parser.sections():
        key = section
        configs[key] = dict(config_parser.items(section))

    return configs

if __name__ == '__main__':
    if len(sys.argv) < 2 or len(sys.argv) > 3:
        show_usage()

    script_filename = sys.argv[1]
    if not os.path.isfile(script_filename):
        raise SystemExit('Could not find script file %s' % script_filename)

    configs = {}

    config_filename = sys.argv[2]
    if not os.path.isfile(config_filename):
        raise SystemExit('Could not find config %s' % config_filename)

    configs = parse_configs(config_filename)

    script_module = imp.load_source('script_module', script_filename)

    script_name = script_module.SCRIPT_NAME
    script_run = script_module.run

    run_as_script(script_name, script_run, config_filename)

